package com.minisoft.online;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
import java.util.Comparator;

public class ApiAccessAnalyzer {
    public static void main(String[] args) {
        String logFilePath = "D:\\temp\\OnlineSalesBatchSvc.log_1";
        analyzeApiAccess(logFilePath);
    }

    public static void analyzeApiAccess(String filePath) {
        // 用于存储接口访问统计的Map，key为接口路径，value为访问次数
        Map<String, Integer> apiAccessCount = new HashMap<>();
        int totalAccess = 0;

        // 正则表达式匹配接口路径信息
        Pattern pattern = Pattern.compile("\"path\":\"([^\"]+)\"");

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    String apiPath = matcher.group(1);
                    apiAccessCount.put(apiPath, apiAccessCount.getOrDefault(apiPath, 0) + 1);
                    totalAccess++;
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading log file: " + e.getMessage());
            return;
        }

        // 打印统计结果
        System.out.println("接口访问统计结果:");
        System.out.println("总访问次数: " + totalAccess);
        System.out.println("不同接口数量: " + apiAccessCount.size());
        
        if (totalAccess > 0) {
            System.out.println("\n各接口访问次数 (按访问量降序排列):");
            
            // 按访问次数降序排序
            Map<String, Integer> sortedApiAccess = apiAccessCount.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
                ));
            
            // 打印排序后的结果
            for (Map.Entry<String, Integer> entry : sortedApiAccess.entrySet()) {
                System.out.printf("%-40s: %d 次 (%.1f%%)%n", 
                    entry.getKey(), 
                    entry.getValue(),
                    (entry.getValue() * 100.0 / totalAccess));
            }
        }
    }
}